package analyse

import (
	"github.com/gofiber/fiber/v2"
	"sg-backend/global"
	"sg-backend/model/paylog"
	"sg-backend/utils"
	"strconv"
	"time"
)

type _monthDataJson struct {
	XData  []int `json:"xData"`
	YData1 []any `json:"yData1"`
	YData2 []any `json:"yData2"`
}

// 根据传入的月份，获取当月每天的收入支出数据，用作线图

func GetMonthPayAndIncomeData(ctx *fiber.Ctx) error {
	// 获取月份
	month := ctx.Query("month")
	if month == "" {
		month = time.Now().Format("2006-01")
	}

	// 字符串转时间
	cstZone := time.FixedZone("CST", 8*3600)
	monthT, _ := time.ParseInLocation("2006-01", month, cstZone)

	// 获取选定的月份有几天
	monthHaveDays := utils.GetYearMonthToDay(monthT.Year(), int(monthT.Month()))

	// X轴
	var xData []int
	startDay := int(1)
	for {
		if startDay <= monthHaveDays {
			xData = append(xData, startDay)
		}
		startDay++
		if startDay > monthHaveDays {
			break
		}
	}

	// 支出Y轴
	var yData1 []any
	for _, v := range xData {
		startTime := monthT.Format("2006-01-") + strconv.Itoa(v) + " 00:00:00"
		endTime := monthT.Format("2006-01-") + strconv.Itoa(v) + " 23:59:59"
		var paymentLog []paylog.PayLog
		if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
			Where("time >= ? AND time <= ?", startTime, endTime).
			Find(&paymentLog); err.Error != nil {
			return ctx.JSON(fiber.Map{
				"status":  "error",
				"message": "获取指定月份支出数据出错！" + err.Error.Error(),
			})
		}

		// 汇总
		var total = float64(0)
		for _, x := range paymentLog {
			total = total + x.Money - x.Refund // 减去退款才是真的支出
		}
		total = utils.NumberToStr(total)
		yData1 = append(yData1, total)
	}

	// 收入Y轴
	var yData2 []any
	for _, v := range xData {
		startTime := monthT.Format("2006-01-") + strconv.Itoa(v) + " 00:00:00"
		endTime := monthT.Format("2006-01-") + strconv.Itoa(v) + " 23:59:59"
		var incomeLog []paylog.IncomeLog
		if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
			Where("time >= ? AND time <= ?", startTime, endTime).
			Find(&incomeLog); err.Error != nil {
			return ctx.JSON(fiber.Map{
				"status":  "error",
				"message": "获取指定月份收入数据出错！" + err.Error.Error(),
			})
		}

		// 汇总
		var total = float64(0)
		for _, x := range incomeLog {
			total = total + x.Money
		}
		total = utils.NumberToStr(total)
		yData2 = append(yData2, total)
	}

	return ctx.JSON(fiber.Map{
		"status": "done",
		"data": _monthDataJson{
			XData:  xData,
			YData1: yData1,
			YData2: yData2,
		},
	})
}
